package com.c3w.synchro.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.annotation.Scope;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * User: P.Lalonde
 * Date: 12-11-15
 * <p/>
 * Classe utilitaire qui me permet de ne pas avoir à propager ces éléments dans tous les controlleurs.
 */
@Scope("request")
public abstract class AbstractApplicationController implements ApplicationContextAware, MessageSourceAware {
    private final Logger logger = Logger.getLogger(getClass().getSimpleName());

    private ApplicationContext applicationContext;

    @Autowired
    private HttpServletRequest request;
    private MessageSource messageSource;

    /**
     * On accède aux dictionnaires et on retourne la valeur correspondant à la clé.
     *
     * @param messageKey La clé pour retrouver le message.
     * @return Le message.
     */
    protected String getMessage(final String messageKey) {
        Locale requestLocale = request.getLocale();
        String message = messageSource.getMessage(messageKey, null, requestLocale);

        if (logger.isDebugEnabled() && messageKey.compareTo(message) == 0) {
            logger.debug("Key not found. [" + messageKey + ", locale:" + requestLocale + "]");
        }

        return message;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}
